/**
 * Created by user on 2015/9/21.
 */

angular.module('mis.cardManager.controllers', [])
    .controller('cardCtrl', ['$scope','$http', '$location', function ($scope, $http, $location) {


        $scope.currentPage = 1;
        $scope.pageSize = 15;

        //分页
        $scope.pagination = new pagination({currentPage:$scope.currentPage,pageSize: $scope.pageSize,
            url:'http://' + backOfficeHost + '/rest/v1.0/mis/card/cardList/:page/:size',
            ajax: $http,
            success:function(data){
                $scope.resultList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共"+$scope.pageNumber+"页 有"+$scope.count+"数据");
            },
            error: function(err){
                //$scope.communityList = null;
            },
            params: {}
        });

        //全选列表
        $scope.allSelected = function () {
            $scope.pagination.allSelected();
        };

        //级联框
        var cascadData = {
            provinceUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionPrivince',
            cityUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCity',
            cityAreaUrl: 'http://' + backOfficeHost + '/rest/v1.0/backoffice/region/regionCounty',
            villageUrl: 'http://' + backOfficeHost + '/rest/v1.0/mis/community/communityList',
            ajax: $http
        };
        $scope.cascading = new gObj.cascading(cascadData);
        $scope.cascading.paint($(".city-cascading")[0],false, 'list');

        $scope.selectFile = function (files) {
            $scope.image = files[0];

            var reader = null;
            if (FileReader) {
                reader = new FileReader();
            } else {
                alert("浏览器暂时不支持FileReader");
            }

            reader.readAsDataURL(files[0]);
            reader.onload = function () {
                $('#logo').attr("src", reader.result);
            };
        };

        //新增
        $scope.add = function(addData, temp){

            var target = temp.target;

            if(!addData){alert('请填写数据!');return;};
            if(!addData.openType){alert('请选择打开方式!');return;};
            if(!addData.beginDate){alert('请选择开始日期!');return;};
            if(!addData.endDate){alert('请选择结束日期!');return;};

            var opt = {
                title : addData.cardTitle
                ,desc : addData.cardDesc
                ,url: addData.url
                //,contentId : getQueryString(addData.url,'topicId')
                ,openType :addData.openType
                ,beginDate : addData.beginDate
                ,endDate : addData.endDate
                ,cardOrder : addData.cardOrder
            };

            if(addData.openType == 4){
                if(!addData.url){alert('请填写URL!');return;};
                opt.contentId  = getQueryString(addData.url,'topicId');
                if(!opt.contentId){alert('URL缺少参数[topicId]!');return;};
            };


            if(addData.url){
                if(getQueryString(addData.url,'topicId') && addData.openType == 3){
                    alert('请检查打开方式和URL是否匹配');
                    return;
                };

            }

            var provinceId = $scope.cascading.getProvince (target);
            var cityId = $scope.cascading.getCity (target);
            var countyId = $scope.cascading.getCityArea (target);

            if(provinceId && !cityId){
                alert('请选择城市!');
                return;
            };

            var level = 0;
            if (provinceId) {
                opt.provinceId = provinceId;
                level = 1;
            };
            if (cityId) {
                opt.cityId = cityId;
                level = 2;
            };
            if (countyId) {
                opt.countyId = countyId;
                level = 3;
            };

            //var contentId = getQueryString(addData.url,'topicId');
            //if(!contentId) opt.openType  =3;

            opt['level']= level;

            if ($scope.image != null) {
                var fd = new FormData();
                fd.append('image1', $scope.image);
                //上传图片
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {
                    opt.imageURL= images.data[0];
                    $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/card/cardAdd', opt, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        $scope.addData = {};
                        $scope.pagination.selectPage(1);//插入成功显示第一页
                        $('#doc-modal-add').modal("close");
                        alert("添加卡片成功");

                    }).error(function (err) {
                        alert(err);
                    });

                });

            }else{

                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/card/cardAdd', opt, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.addData = {};
                    $scope.pagination.selectPage(1);//插入成功显示第一页
                    $('#doc-modal-add').modal("close");
                    alert("添加卡片成功");

                }).error(function (err) {
                    alert(err);
                });
            };

        };

        //删除
        $scope.delete = function(){
            var params = {
                url: 'http://' + backOfficeHost + '/rest/v1.0/mis/card/cardDelete',
                checkObj: $(".item-check"),//checkbox对象
                key: "cardID",
                success: function(data){
                    var number = $(".am-active").text();//当前页码
                    $scope.pagination.selectPage(number);
                    alert("删除成功！");
                    //$scope.menuUpdate(data);
                },
                error: function(){}
            };
            $scope.pagination.listDelete(params);
        };

        $scope.updateData = {};
        //$scope.updateData.cardTitle = null;
        //$scope.updateData.cardDesc = null;
        //$scope.updateData.imageURL = null;
        //$scope.updateData.url = null;
        //编辑
        $scope.cardEdit = function(card) {

            $scope.cascading.paint($("#cascad-edit")[0], false, 'edit');


            console.debug(card);
            //$scope.updateDate.cardTitle = card.title;
            //$scope.updateDate.cardDesc = card.desc;
            //$scope.updateDate.imageURL = card.imageURL;
            //$scope.updateDate.url = card.url;
            card.beginDate = (new Date(card.beginDate)).format('yyyy-MM-dd hh:mm');
            card.endDate = (new Date(card.endDate)).format('yyyy-MM-dd hh:mm');
            $scope.updateDate = card;
            //$scope.cardTitle = card.title;
            //$scope.cardDesc = card.desc;
            //$scope.beginDate = new Date(card.beginDate).format('yyyy-MM-dd');
            //document.getElementById('begin').valueAsDate = new Date(card.beginDate);
            //document.getElementById('end').valueAsDate = new Date(card.endDate);
            //document.getElementById('begin').value  = (new Date(card.beginDate)).format('yyyy-MM-dd hh:mm');
            //document.getElementById('end').value  = (new Date(card.endDate)).format('yyyy-MM-dd hh:mm');

            if (card.province) {
                $scope.cascading.paint($("#cascad-edit")[0], false);
                $("#cascad-edit").find(".c-provinces").val(card.province.name);
                if (card.province)$("#cascad-edit").find(".c-provinces")[0].dataset.cId = card.province.objId;
            }
            if (card.city) {
                $("#cascad-edit").find(".c-citys").val(card.city.name);
                if (card.city)$("#cascad-edit").find(".c-citys")[0].dataset.cId = card.city.objId;
            };
            if (card.county) {
                $("#cascad-edit").find(".c-cityArea").val(card.county.name);
                if (card.county)$("#cascad-edit").find(".c-cityArea")[0].dataset.cId = card.county.objId;
            }
            //$("#cascad-edit").find(".c-citys").val(listData.cityId.name);
            //if(listData.cityId)$("#cascad-edit").find(".c-citys")[0].dataset.cId = listData.cityId.objId;
            //$("#cascad-edit").find(".c-cityArea").val(listData.countyId.name);
            //if(listData.countyId)$("#cascad-edit").find(".c-cityArea")[0].dataset.cId = listData.countyId.objId;

            $('#doc-modal-edit').modal({target: '#doc-modal-edit', width: 800, height: 600});
        };

        //编辑
        $scope.update = function(updateData,temp){
            var target = temp.target;

            if(!updateData){alert('请填写数据!');return;};
            if(!updateData.openType){alert('请选择打开方式!');return;};
            if(!updateData.beginDate){alert('请选择开始日期!');return;};
            if(!updateData.endDate){alert('请选择结束日期!');return;};

            var uData = {cardID:"",card:{}};
            if(updateData.objId)uData.cardID = updateData.objId;

            if(updateData.title != null)uData.card.title = updateData.title;
            if(updateData.desc != null)uData.card.desc = updateData.desc;
            if(updateData.cardOrder != null)uData.card.cardOrder = updateData.cardOrder;
            if(updateData.openType != null)uData.card.openType = updateData.openType;

            if(updateData.url != null){
                uData.card.url = updateData.url;
                if(updateData.openType == 4) {
                    uData.card.contentId = getQueryString(uData.card.url, 'topicId');
                    if(!uData.card.contentId){alert('URL缺少参数[topicId]!');return;};
                };
            };
            if(updateData.beginDate != null)uData.card.beginDate = updateData.beginDate;
            if(updateData.endDate != null)uData.card.endDate = updateData.endDate;

            var provinceId = $scope.cascading.getProvince (target);
            var cityId = $scope.cascading.getCity (target);
            var countyId = $scope.cascading.getCityArea (target);

            if(provinceId && !cityId){
                alert('请选择城市!');
                return;
            };

            var level = 0;
            if (provinceId) {
                uData.card.province = provinceId;
                level =1;
            };
            if (cityId) {
                uData.card.city = cityId;
                level =2;
            }
            if (countyId) {
                uData.card.county = countyId;
                level =3;
            }
            uData.card.level = level;
            //uData.card.openType = 4;
            //if(!uData.card.contentId){uData.card.openType =3;};


            if($scope.image){

                var fd = new FormData();
                fd.append('image1', $scope.image);
                //上传图片
                $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/common/uploadImage', fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }).success(function (images) {

                    uData.card.imageURL= images.data[0];

                    var params = {
                        url: 'http://' + backOfficeHost + '/rest/v1.0/mis/card/cardEdit',
                        updateData: uData,
                        success: function(data){
                            var pageNumber = $(".am-active").text();//当前页码
                            $('#doc-modal-edit').modal("close");
                            $scope.pagination.selectPage(pageNumber);
                            if(data.result.status == 1){
                                alert("修改成功！");
                            }else{
                                alert("修改失败！");
                            }
                        },
                        error: function(){
                            var number = $(".am-active").text();//当前页码
                            $('#doc-modal-edit').modal("close");
                            alert("修改失败！");
                        }
                    };
                    $scope.pagination.listUpdate(params);

                })


            }else {

                var params = {
                    url: 'http://' + backOfficeHost + '/rest/v1.0/mis/card/cardEdit',
                    updateData: uData,
                    success: function(data){
                        var pageNumber = $(".am-active").text();//当前页码
                        $('#doc-modal-edit').modal("close");
                        $scope.pagination.selectPage(pageNumber);
                        if(data.result.status == 1){
                            alert("修改成功！");
                        }else{
                            alert("修改失败！");
                        }
                    },
                    error: function(){
                        var number = $(".am-active").text();//当前页码
                        $('#doc-modal-edit').modal("close");
                        alert("修改失败！");
                    }
                };
                $scope.pagination.listUpdate(params);

            };
        };


        //搜索
        $scope.search = function (temp) {

            var btn = temp.target;
            var opt = {};
            //if (countyId) body.countyId = countyId;
            if ($scope.cardTitle) opt.title = $scope.cardTitle;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/card/cardList/' + 1 + '/' + $scope.pageSize, opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;

                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $scope.pagination.searchParams = opt;
            }).error(function (err) {
                alert(err);
            });

        };


        $scope.cardPushShow = function(card){

            $scope.cardPush = card;
            $scope.pushMsg ='';

            if(!card.title) {alert('卡片没有标题，无法推送！'); return};
            if(!card.url &&(card.openType==3 || card.openType==4) ) {alert('卡片没有起关联url，无法推送！'); return};
            if(!card.level) {alert('卡片没有选择推送区域，无法推送！'); return};
            if(!card.beginDate) {alert('卡片没有开始时间，无法推送！'); return};
            if(!card.endDate) {alert('卡片没有结束时间，无法推送！'); return};

            $('#doc-modal-push').modal({target: '#doc-modal-push', width: 800, height: 360 });

        };


        $scope.cardPushMsg = function(msg){

            if(!$scope.pushMsg){
                alert('请填写推送内容!');
                return;
            }

            var pushCommunity ={};

            if($scope.cardPush.province) pushCommunity.provinceId = $scope.cardPush.province.objId;
            if($scope.cardPush.city) pushCommunity.cityId = $scope.cardPush.city.objId;
            if($scope.cardPush.county) pushCommunity.countyId = $scope.cardPush.county.objId;
            var contentId;
            if($scope.cardPush.openType ==3)
            {
                contentId = getQueryString($scope.cardPush.url,'activityId');
            }
            else if($scope.cardPush.openType==4){
                contentId = getQueryString($scope.cardPush.url,'topicId');
            };
            //if($scope.cardPush.url){
            //    contentId = getQueryString($scope.cardPush.url,'activityId');
            //    if(!contentId){
            //        contentId = getQueryString($scope.cardPush.url,'topicId');
            //    }
            //};

            //var openType = 4;
            //if(!contentId) openType  =3;

            var opt = {
                level:$scope.cardPush.level,
                tag: '卡片',
                url: $scope.cardPush.url,
                openType: $scope.cardPush.openType,
                contentId: contentId,
                desc: msg,
                pushCommunity : pushCommunity

            };

            if($scope.cardPush.level =='2'){
                opt.tags = [$scope.cardPush.city.name];
            };

            //console.debug(opt);
            $('#doc-modal-push').modal("close");
            $('#loading').modal({target: '#loading'});

            if(opt.url) {
                var parm = getQueryString(opt.url, 'topicId');
                if (parm) {
                    //$http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/shortUrl', {url: opt.url}, {
                    //    headers: {'Content-Type': 'application/json;charset=utf-8'}
                    //}).success(function (data) {
                    opt.url = opt.url.substr(0, opt.url.indexOf('?'));
                }
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/card/cardPush', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                if (data.result.status == 1) {
                    $('#loading').modal("close");

                    alert("卡片推送完成！");
                } else {
                    alert("卡片推送失败！");
                    //$scope.pagination.selectPage($scope.currentPage);
                }

            }).error(function (err) {
                $('#loading').modal("close");
                alert("卡片推送失败！");
                //$scope.pagination.selectPage($scope.currentPage);
            });


                //}).error(function (err) {
                //    $('#loading').modal("close");
                //    alert("获取短连接失败！");
                //    //$scope.pagination.selectPage($scope.currentPage);
                //});


            //}else{
            //
            //    $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/card/cardPush', opt, {
            //        headers: {'Content-Type': 'application/json;charset=utf-8'}
            //    }).success(function (data) {
            //
            //        if (data.result.status == 1) {
            //            $('#loading').modal("close");
            //
            //            alert("卡片推送完成！");
            //        } else {
            //            alert("卡片推送失败！");
            //            //$scope.pagination.selectPage($scope.currentPage);
            //        }
            //
            //    }).error(function (err) {
            //        $('#loading').modal("close");
            //        alert("卡片推送失败！");
            //        //$scope.pagination.selectPage($scope.currentPage);
            //    });
            //
            //};

        };


    }]);